//
//  KeyboardEmoticonPackage.swift
//  Emoji
//
//  Created by 钟清 on 17/4/11.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

class KeyboardEmoticonPackage: NSObject {
    /* 当前组名 */
    var group_name_cn: String?
    /* 当前文件夹名称 */
    var id: String?
    /* 当前组所有的表情 */
    var emoticons: [KeyboardEmoticons]?
    
    init(id: String) {
        self.id = id
    }
    
    /* 加载所有组数据 */
    class func loadEmoticonPackages() -> [KeyboardEmoticonPackage] {
        var models = [KeyboardEmoticonPackage]()
        /* 手动添加最近组 */
        let package = KeyboardEmoticonPackage(id: "")
        package.appendEmptyEmoticons()
        models.append(package)
        /* 添加其他组 */
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        let dict = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String : AnyObject]]
        for packageDict in array {
            let package = KeyboardEmoticonPackage(id: packageDict["id"] as! String)
            /* 下载每一组的数据 */
            package.loadEmoticons()
            /* 下载每一组的数据 */
            package.appendEmptyEmoticons()
            models.append(package)
        }
        return models
    }
    /* 下载每一组的数据 */
    private func loadEmoticons() {
        let path = NSBundle.mainBundle().pathForResource(self.id, ofType: nil, inDirectory: "Emoticons.bundle")
        let filePath = (path! as NSString).stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: filePath)!
        group_name_cn = dict["group_name_cn"] as? String
        let array = dict["emoticons"] as! [[String : AnyObject]]
        var models = [KeyboardEmoticons]()
        var index = 0
        for emoticonDict in array {
            /* 判断是否是第21个 */
            if index == 20 {
                /* 添加删除按钮 */
                let emoticon = KeyboardEmoticons(isRemoveButton: true)
                models.append(emoticon)
                index = 0
                continue
            }
            let emoticon = KeyboardEmoticons(dict: emoticonDict, id: self.id!)
            models.append(emoticon)
            index += 1
        }
        emoticons = models
    }
    /* 将组数据补空 */
    private func appendEmptyEmoticons() {
        /* 判断是否是最近组 */
        if emoticons == nil {
            emoticons = [KeyboardEmoticons]()
        }
        
        let number = emoticons!.count % 21
        for _ in number..<20 { // 补空范围
            let emoticon = KeyboardEmoticons(isRemoveButton: false)
            emoticons?.append(emoticon)
        }
        /* 第21个空添加删除按钮 */
        let emoticon = KeyboardEmoticons(isRemoveButton: true)
        emoticons?.append(emoticon)
    }
    /* 添加最近表情 */
    func addFavouriteEmoticon(emoticon: KeyboardEmoticons) {
        /* 先移除删除按钮 */
        emoticons?.removeLast()
        /* 不包含传入的emoticon,则先移除后添加 */
        if !emoticons!.contains(emoticon) {
            emoticons?.removeLast()
            emoticons?.append(emoticon)
        }
        /* 排序 */
        let array = emoticons?.sort({ (e1, e2) -> Bool in
            return e1.count > e2.count
        })
        emoticons = array
        /* 添加删除按钮 */
        emoticons?.append(KeyboardEmoticons(isRemoveButton: true))
    }
}

// MARK: - NSRegularExpression
extension KeyboardEmoticonPackage {
    class func createMutableAttributedStr(str: String, font: UIFont) -> NSMutableAttributedString {
        /* 表情的规则 */
        let pattern = "\\[.*?\\]"
        /* 正则表达式对象 */
        let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
        /* 匹配结果 */
        let results = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: str.characters.count))
        /* str对应的可变属性字符串 */
        let attributedMutableStr = NSMutableAttributedString(string: str)
        for var i = results.count - 1; i >= 0; i-=1 {
            /* 倒序，取出chs */
            let result = results[i]
            let chs = (str as NSString).substringWithRange(result.range)
            /* 获取pngPath */
            let pngPath = findPngPath(chs)
            /* 获取表情对应的属性字符串 */
            guard let tempPngPth = pngPath else {
                continue
            }
            let attachment = NSTextAttachment()
            attachment.image = UIImage(contentsOfFile: tempPngPth)
            attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            let emoticonAttributedStr = NSAttributedString(attachment: attachment)
            /* 替换 */
            attributedMutableStr.replaceCharactersInRange(result.range, withAttributedString: emoticonAttributedStr)
        }
        return attributedMutableStr
    }
    
    class func findPngPath(chs: String) -> String? {
        /*  加载所有包 */
        let packages = KeyboardEmoticonPackage.loadEmoticonPackages()
        /* 遍历,用chs拿到pngPath */
        for package in packages { // 遍历包拿表情
            guard let emoticons = package.emoticons else {
                ZQLog("该表情包没有值")
                continue
            }
            var tempPngPath : String?
            for emoticon in emoticons { // 遍历表情拿chs
                guard let emoticonChs = emoticon.chs else {
                    ZQLog("该表情没有chs")
                    continue
                }
                if emoticonChs == chs { // 匹对chs拿pngPath
                    tempPngPath = emoticon.pngPath
                    break
                }
            }
            if tempPngPath != nil {
                return tempPngPath
            }
        }
        return nil
    }
}

class KeyboardEmoticons: NSObject {
    /* 当前对应文件夹名称 */
    var id: String?
    /* 当前表情对应字符串 */
    var chs: String?
    /* 当前表情对应图片 */
    var png: String? {
        didSet {
            let path = NSBundle.mainBundle().pathForResource(id, ofType: nil, inDirectory: "Emoticons.bundle")!
            pngPath = (path as NSString).stringByAppendingPathComponent(png ?? "")
        }
    }
    /* 当前表情对应图片的路劲 */
    var pngPath: String?
    /* apple emoji对应十六进制字符串 */
    var code: String? {
        didSet{
            /* 扫描器 */
            let sanner = NSScanner(string: code ?? "0")
            /* 扫描出对应的16进制 */
            var result: UInt32 = 0
            sanner.scanHexInt(&result)
            /* 创建字符串 */
            emoticonStr = "\(Character(UnicodeScalar(result)))"
        }
    }
    /* 转换后的emoji表情字符串 */
    var emoticonStr: String?
    /* 标记：是否是删除按钮 */
    var isRemoveButton: Bool = false
    /* 记录表情使用次数 */
    var count: Int = 0
    
    init(dict: [String : AnyObject], id: String) {
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    /* 重写，获取空的Emoticons */
//    override init() {
//        super.init()
//    }
    init(isRemoveButton: Bool) {
        self.isRemoveButton = isRemoveButton
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}
